const GRADIENT_PALETTES = [
    { gradient: 'linear-gradient(140deg, #ff6a3d, #ff8e53)', textColor: '#fff', icon: '⭐' },
    { gradient: 'linear-gradient(140deg, #6366f1, #8b5cf6)', textColor: '#f8fafc', icon: '⚡' },
    { gradient: 'linear-gradient(140deg, #0ea5e9, #2563eb)', textColor: '#f8fafc', icon: '📘' },
    { gradient: 'linear-gradient(140deg, #ec4899, #f97316)', textColor: '#fff5f5', icon: '💡' },
    { gradient: 'linear-gradient(140deg, #22c55e, #16a34a)', textColor: '#f0fdf4', icon: '🌿' },
    { gradient: 'linear-gradient(140deg, #9333ea, #c026d3)', textColor: '#fdf4ff', icon: '✨' },
    { gradient: 'linear-gradient(140deg, #facc15, #f97316)', textColor: '#1f2937', icon: '🔥' },
    { gradient: 'linear-gradient(140deg, #14b8a6, #0f766e)', textColor: '#ecfeff', icon: '🎯' },
]

/**
 * 将字符串映射为稳定的整数
 * @param {string} input
 * @returns {number}
 */
function hashString(input = '') {
    if (!input) return 0
    let hash = 0
    const str = input.toString()
    for (let i = 0; i < str.length; i += 1) {
        hash = (hash << 5) - hash + str.charCodeAt(i)
        hash |= 0 // 转为 32 位整数
    }
    return Math.abs(hash)
}

/**
 * 将词书名称拆分为 1~3 行，适配中文和英文
 * @param {string} name
 * @returns {string[]}
 */
function splitNameLines(name = '') {
    if (!name) return ['词书']

    const trimmed = name.trim()
    // 如果包含空格，按照单词拆分
    if (/\s/.test(trimmed)) {
        const words = trimmed.split(/\s+/)
        const lines = []
        let current = ''
        words.forEach((word) => {
            const next = current ? `${current} ${word}` : word
            if (next.length > 10 && current) {
                lines.push(current)
                current = word
            } else {
                current = next
            }
        })
        if (current) {
            lines.push(current)
        }
        return lines.slice(0, 3)
    }

    // 中文或无空格，按字符长度拆分
    const chars = Array.from(trimmed)
    const maxLen = trimmed.length <= 6 ? trimmed.length : 6
    const chunkSize = Math.max(3, Math.min(6, maxLen))
    const lines = []
    for (let i = 0; i < chars.length; i += chunkSize) {
        lines.push(chars.slice(i, i + chunkSize).join(''))
        if (lines.length === 3) break
    }
    return lines
}

/**
 * 根据词书名称生成渐变封面配置
 * @param {string} name
 * @returns {{ gradient: string, icon: string, textColor: string, lines: string[] }}
 */
export function generateWordbookCover(name) {
    const hash = hashString(name)
    const palette = GRADIENT_PALETTES[hash % GRADIENT_PALETTES.length]

    const lines = splitNameLines(name)
    const iconChoices = ['⭐', '⚡', '📘', '🚀', '🧠', '📚', '✍️', '🌟', '🎯', '🔮']
    const icon = iconChoices[hash % iconChoices.length] || palette.icon

    return {
        gradient: palette.gradient,
        icon: palette.icon || icon,
        textColor: palette.textColor || '#fff',
        lines,
    }
}


